package com.czk.netty.netty.groupchat.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * 心跳检测机制
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/18 21:25
 */
public class MyServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建服务器
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 添加日志处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // IdleStateHandler netty提供的空闲处理的处理器
                            /**
                             * arg1 IdleStateHandler  netty提供的空闲处理的处理器
                             * agr2 readerIdleTime 表示多长时间没有读，就会发生一个心跳检测包是否连接
                             * arg3 writerIdleTime: 表示多长时间没写，就会发送一个心跳检测报告是否连接
                             * arg4 allIdleTime：表示多长时间没有读写，就会发送一个心跳检测报告是否连接
                             */
                            // 此handler触发后，就会传递给管道的下一个handler的userEvenTriggered方法来来处理
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            // 加入一个对空闲检测的进一步处理的handler
                            pipeline.addLast(new MyServerHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.bind(7001).sync();
        } catch (Exception ex) {

        } finally {

        }
    }
}
